package com.hsy.swu.hsyutils

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.os.Environment
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.graphics.drawable.toBitmap
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException


fun Context.fileWrite(string: String, fileName: String) {
    val file = File(filesDir, fileName)
    try {
        val writer = BufferedWriter(FileWriter(file))
        writer.write(string)
        writer.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

fun Context.fileRead(fileName: String): String {
    val file = File(filesDir, fileName)
    var result = ""
    try {
        val reader = BufferedReader(FileReader(file))
        var line: String?
        val content = StringBuilder()

        while (reader.readLine().also { line = it } != null) {
            content.append(line)
        }
        reader.close()
        result = content.toString()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return result
}

fun Context.fileDelete(fileName: String) {
    val file = File(filesDir, fileName)
    try {
        if (file.exists()) file.delete()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun AppCompatImageView.saveImgToAlbum(toSaveName: String) {
    val albumPath =
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath
    val toSaveImgPath = File(albumPath, "$toSaveName.jpg")
    try {
        val os = FileOutputStream(toSaveImgPath)
        val bitmap = drawable.toBitmap(1440, 2560)
        var byteArray: ByteArray
        ByteArrayOutputStream().use { stream ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            byteArray = stream.toByteArray()
        }
        os.write(byteArray)
        os.close()

        // 保存之后要扫描相册才能刷新
        MediaScannerConnection.scanFile(context, arrayOf(toSaveImgPath.absolutePath), null, null)
        MActivityUtil.showToast("已保存至相册")
    } catch (ex: IOException) {
        ex.printStackTrace()
        MActivityUtil.showToast("保存失败")
    }
}